package com.kun.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.kun.entity.User;
import com.kun.entity.UserExample;
import com.kun.entity.UserExample.Criteria;
import com.kun.mapper.cluster.custom.UserMapperRCustom;
import com.kun.mapper.master.MasterUserMapper;
import com.kun.service.UserService;
import com.kun.util.GenerateRandomNumber;
import com.kun.util.MD5ProducterUtil;
import com.kun.util.PaginationUtil;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private MasterUserMapper masterUserMapper;
	
	@Autowired
	private UserMapperRCustom userMapperRCustom;

	final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
	final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	@Override
	public User selectUserByLogUsername(String username) {
		UserExample uex = new UserExample();
		Criteria criteria = uex.createCriteria();
		if(Pattern.matches(REGEX_MOBILE, username)){
			criteria.andPhoneEqualTo(username);
		}else if(Pattern.matches(REGEX_EMAIL, username)){
			criteria.andEmailEqualTo(username);
		}else{
			criteria.andUsernameEqualTo(username);
		}
		List<User> userList = userMapperRCustom.selectByExample(uex);
		if(userList.size()>0){
			return userList.get(0);
		}else{
			return null;
		}
	}

	@Override
	public int updateUser(User user, UserExample uExample) {
		return masterUserMapper.updateByExampleSelective(user, uExample);
	}

	@Override
	public User selectByPrimaryKey(String id) {
		return userMapperRCustom.selectByPrimaryKey(id);
	}

	/* 
	 * 注册业务实现类
	 */
	@Override
	public int insertUser(User user) {
		String username = "u" + GenerateRandomNumber.getCharAndNumr(6);//随机生成username
		String realSalt = GenerateRandomNumber.getCharAndNumr(10);
		String saltString = username + realSalt;
		String password = MD5ProducterUtil.generate(user.getPassword(), saltString);
		user.setId(UUID.randomUUID().toString());
		user.setState(1);
		user.setAuthProcess(0);
		user.setSalt(realSalt);
		user.setUsername(username);
		user.setPassword(password);
		user.setRegDate(new Date());
		user.setHeadImg("https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com/userImg/default.jpeg");
		user.setAuthProcess(0);
		if(user.getNickname()==null){
			user.setNickname(username);
		}
		return masterUserMapper.insert(user);
	}

	/**
	 * 更新整个user
	 * */
	@Override
	public int updateUserAllInfo(User user) {
		return masterUserMapper.updateByPrimaryKey(user);
	}

	
	
	/**
	 * username用户查询
	 * */
	@Override
	public User selectUserByRealUsername(String username) {
		UserExample uex = new UserExample();
		Criteria criteria = uex.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<User> l = userMapperRCustom.selectByExample(uex);
		if(l.size()>0){
			return l.get(0);
		}else{
			return null;
		}
	}
	
	
	/**
	 * nickname realname模糊查询 
	 * return List<userId>
	 * */
	@Override
	public List<String> selectUserByLikeNicknameOrRealame(String nickname,String realname) {
		if(nickname==null){
			nickname="";
		}
		if(realname==null){
			realname="";
		}
		if("".equals(nickname)&&"".equals(realname)){
			return null;//不输入值返回null
		}
		List<String> l = new ArrayList<String>();
		l = userMapperRCustom.selectPrimaryKeyLikeNickName(nickname,realname);
		return l;
	}
	
	/**
	 * only nickname查询id
	 * */
	public List<String> selectUserByLikeNickname(String nickname) {
		if("".equals(nickname)||nickname==null){
			return null;//不输入值返回null
		}
		List<String> l = new ArrayList<String>();
		l = userMapperRCustom.selectPrimaryOnlyLikeNickName(nickname);
		return l;
	}
	
	
	
	public List<String> selectUserByRealameAndIdcard(String realname,String idCard) {
		if(idCard==null){
			idCard="";
		}
		if(realname==null){
			realname="";
		}
		if("".equals(idCard)&&"".equals(realname)){
			return null;//不输入值返回null
		}
		List<String> l = new ArrayList<String>();
		l = userMapperRCustom.selectUserByRealameAndIdcard(realname,idCard);
		return l;
	}
	

	/**
	 * 根据username 更新普通用户信息
	 * */
	@Override
	public int updateUserSimpleInfoByUsername(String username,User user) {
		String id ="";
		if(!"".equals(username)&&username!=null){
			if(Pattern.matches(REGEX_MOBILE, username)){
				id = userMapperRCustom.selectPrimaryKeyByPhone(username);
			}else if(Pattern.matches(REGEX_EMAIL, username)){
				id = userMapperRCustom.selectPrimaryKeyByEmail(username);
			}else{
				return 0;
			}
		}
		if(!"".equals(id)&&id!=null){
			user.setId(id);
			masterUserMapper.updateByPrimaryKeySelective(user);
			return 1;
		}else{
			return 0;
		}
	}

	@Override
	public int updateUserByIdSelective(User user) {
		return masterUserMapper.updateByPrimaryKeySelective(user);
	}

	
	/**
	 * 分页条件查询
	 * */
	@SuppressWarnings("rawtypes")
	public Map<String,Object> selectAllUser(int begin,int length,String jsonString,boolean isAuth){
		UserExample bex = new UserExample();
		Criteria criteria = bex.createCriteria();
		if(isAuth==true){
			criteria.andIdcardIsNotNull();
			criteria.andRealnameIsNotNull();
			criteria.andAddressIsNotNull();
			criteria.andSexIsNotNull();
			criteria.andAuthProcessEqualTo(0);
		}
		criteria.andStateNotEqualTo(9);
		if(!"".equals(jsonString)&&jsonString!=null&&jsonString.length()>0){
			JSONObject json = JSONObject.parseObject(jsonString);
			Map cMap = (Map)json;
			if (cMap != null && !cMap.isEmpty()) {
				Iterator it = cMap.keySet().iterator();
				while(it.hasNext()){
					String name = (String)it.next();
					try {
						if(!cMap.get(name).equals(null)){
							if(name.equals("sex")){//性别查询
								criteria.andSexEqualTo((String)cMap.get(name));
							}else if(name.equals("state")){//状态查询
								criteria.andStateEqualTo((int)cMap.get(name));
							}else if(name.equals("authProcess")){//认证查询
								if(((int)cMap.get(name))==0){//未认证
									criteria.andAuthProcessEqualTo(0);
								}else if(((int)cMap.get(name))==1){//已提交实名信息
									criteria.andAuthProcessEqualTo(1);
								}else if(((int)cMap.get(name))==2){//押金成功认证
									criteria.andAuthProcessEqualTo(2);
								}else if(((int)cMap.get(name))==3){//共享图书成功认证
									criteria.andAuthProcessEqualTo(3);
								}
							}else if(name.equals("afterAuth")){
								criteria.andAuthProcessGreaterThan((int)cMap.get(name));
							}else if(name.equals("nickname")){//昵称查询
								criteria.andNicknameLike("%"+ java.net.URLDecoder.decode((String)cMap.get(name),"UTF-8").trim() +"%");
							}else if(name.equals("realname")){//真实姓名查询
								criteria.andRealnameLike("%"+ java.net.URLDecoder.decode((String)cMap.get(name),"UTF-8").trim() +"%");
							}else if(name.equals("email")){
								criteria.andEmailLike("%"+ java.net.URLDecoder.decode((String)cMap.get(name),"UTF-8").trim() +"%");	
							}else if(name.equals("phone")){
								criteria.andPhoneLike("%"+ java.net.URLDecoder.decode((String)cMap.get(name),"UTF-8").trim() +"%");	
							}else if(name.equals("address")){
								criteria.andAddressLike("%"+ java.net.URLDecoder.decode((String)cMap.get(name),"UTF-8").trim() +"%");	
							}else if(name.equals("integral")){//积分 排序
								bex.setOrderByClause("integral  "+cMap.get(name)); 
							}else if(name.equals("level")){//共享 排序
								criteria.andLevelGreaterThan(0);
								bex.setOrderByClause("level  "+cMap.get(name));
							}
						}
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}
		}
			
		int allRecord = userMapperRCustom.countByExample(bex);
		PaginationUtil pagination = new PaginationUtil((begin-1)*length,length,allRecord);
		bex.setPagination(pagination);
		List<User> userList = userMapperRCustom.selectByExample(bex);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("allRecord", allRecord);
		resultMap.put("userList", userList);
		return resultMap;
	}

	@Override
	public User selectUserByWechat(String openId) {
			if(openId!=null&&!"".equals(openId)){
				UserExample uxe = new UserExample();
				Criteria c = uxe.createCriteria();
				c.andWechatEqualTo(openId);
				List<User> l = userMapperRCustom.selectByExample(uxe);
				if(l.size()>0){
					return l.get(0);
				}else{
					return null;
				}
			}else{
				return null;
			}
	}
	
}
